package com.profgj.profgj.controller;

import com.profgj.profgj.entity.Bill;
import com.profgj.profgj.entity.ProjectBaseInfo;
import com.profgj.profgj.entity.ProjectTotalEnergyconsumption;
import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.service.BillService;
import com.profgj.profgj.service.ProjectBaseInfoService;
import com.profgj.profgj.service.ProjectTotalEnergyconsumptionService;
import com.profgj.profgj.utils.EmptyUtils;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.validater.ProjectBaseInfoValidator;
import com.profgj.profgj.vo.*;
import io.swagger.annotations.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * (项目基本情况)控制层
 *
 * @author 杨帅
 * @since 2021-06-22 11:09:35
 */

/**
 * JSON格式返回数据
 */
@RestController
/**
 * 请求基路径
 */
@RequestMapping("/project")
/**
 * 作用域 回话级别
 */
@Scope("session")
@Api(tags = {"项目基本情况"},description = "项目基本情况")
public class ProjectBaseController {

    /**
     * 临时文件名数组
     */
    private static String[] tempfilename = new String[10];
    /**
     * 文件数组索引
     */
    private static Integer file_index = 0;

    /**
     * 项目基本情况对象
     */
    @Resource
    private ProjectBaseInfoService projectBaseInfoService;

    /**
     * 总能耗服务对象
     */
    @Resource
    private ProjectTotalEnergyconsumptionService projectTotalEnergyconsumptionService;

    /**
     * 票据上传服务对象
     */
    @Resource
    private BillService billService;

    /**
     * 返回空对象替代品
     */
    private EmptyObject emptyObject = new EmptyObject();

    /**
     * servlet文件上传默认路径,作为临时上传路径
     */
    @Value("${spring.servlet.multipart.location}")
    private String temp_path;

    /**
     * 票据存放目录
     */
    @Value("${system.bills}")
    private String des_path;

    /**
     * 初始化设置校验器
      * @param binder   校验器绑定对象
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new ProjectBaseInfoValidator());
    }

    /**
     * 通过id查询项目基本情况
     * @param id    项目基本情况id
     * @param session   Http回话对象内部存储当前登录的用户id  user_id / user_namen / role_id
     * @return
     */
    @GetMapping("/projectbase/{id}")
    @ApiOperation(value = "通过id查询项目基本情况",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id",value = "项目基本情况id",dataType = "Long", paramType = "Long", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> projectBaseQueryByIdMethod(@PathVariable("id")Long id, @ApiIgnore HttpSession session){

        // 判断id是否为空
        if(!EmptyUtils.isLongEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
        ProjectBaseInfoVo projectBaseInfo = null;
        // 如果当前登录的不是管理员用户(企业用户)
        if (role_id != 1) {
            // 获取当前登录的企业用户id 关联到项目基本情况 本关联只用来限制企业用户只查看自己
            projectBaseInfo = projectBaseInfoService.queryByIdAndUserId(id,user_id);
        } else {
            // 根据id查询项目要件数据
            projectBaseInfo = projectBaseInfoService.queryById(id);
        }


        //判断项目要件对象是否为空
        if(!EmptyUtils.isProjectBaseInfoEmpty(projectBaseInfo)) {
            return ReturnOperator.createResultMsg("", ServerStatus.PBI_NOT_EXISTS, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), projectBaseInfo, HttpStatus.OK);
    }



    /**
     * 关键字查询
     * @param draw    绘制次数
     * @param start    查询起始位置
     * @param length     查询条数
     * @param search  关键字
     * @param session   Http回话对象内部存储当前登录的用户id  user_id / user_namen / role_id
     * @return
     */
    @GetMapping("/projectbase/list")
    @ApiOperation(value = "List查询项目基本情况列表",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "draw",value = "绘制次数",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "start",value = "查询起始位置",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "length",value = "查询条数",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "search",value = "查询关键字",dataType = "String", paramType = "String", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ReturnResult> projectBaseQueryWordMethod(Integer draw,
                                                                    Integer start,
                                                                    Integer length,
                                                                    String search,
                                                                    @ApiIgnore HttpSession session){

        // 校验分页参数
        if(!EmptyUtils.isIntegerEmpty(start) && !EmptyUtils.isIntegerEmpty(length)) {
            return ReturnOperator.createResultMsg(draw,0, 0,
                    new ArrayList<>(), HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
        List<ProjectBaseInfoVo> projectBaseInfos = null;

        Integer totalCount = 0;
        // 如果当前登录的不是管理员用户(企业用户)
        if (role_id != 1) {
            // 企业用户的情况下

            // 判断查询的关键字是否为空
            if(EmptyUtils.isStringEmpty(search)) {
                // 不用分页算出总记录数
                totalCount = projectBaseInfoService.queryAllByWordAndUserId(search, user_id).size();
                // 使用当前用户id和关键字查询 项目基本情况
                projectBaseInfos = projectBaseInfoService.queryAllByWordAndUserIdLimit(search, start, length, user_id);
            } else {
                // 不用分页算出总记录数
                totalCount = projectBaseInfoService.queryAllByUserId(user_id).size();
                // 使用当前用户id和关键字查询 项目基本情况
                projectBaseInfos = projectBaseInfoService.queryAllByUserIdLimit(start, length, user_id);
            }

        } else {
            // 管理员的情况下

            // 校验关键字
            if(EmptyUtils.isStringEmpty(search)) {
                // 不用分页算出总记录数
                totalCount = projectBaseInfoService.queryAllByWord(search).size();
                // 项目基本情况关键字查询
                projectBaseInfos = projectBaseInfoService.queryAllByWordLimit(search, start, length);
            } else {
                // 不用分页算出总记录数
                totalCount = projectBaseInfoService.queryAll().size();
                // 项目基本情况关键字查询
                projectBaseInfos = projectBaseInfoService.queryAllByLimit(start, length);
            }

        }


        // 判断列表是否有内容
        if (!EmptyUtils.isProjectBaseInfoListEmpty(projectBaseInfos)) {
            return ReturnOperator.createResultMsg(draw,0, 0,
                    new ArrayList<>(), HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(draw, totalCount,totalCount,
                projectBaseInfos, HttpStatus.OK);
    }


    /**
     * 企业id查询该企业下所有项目
     * @param enId  企业id
     * @return
     */
    @GetMapping("/projectbase/enid/{enId}")
    @ApiOperation(value = "企业id查询该企业下所有项目",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "enId",value = "企业id",dataType = "Long", paramType = "Long", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> projectBaseQueryListByEnIdMethod(@PathVariable("enId")Long enId){

        // 参数校验
        if(!EmptyUtils.isLongEmpty(enId)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 获取企业下所有项目
        List<ProjectBaseInfoVo> projectBaseInfoVoList = projectBaseInfoService.queryByEnId(enId);

        // 查询校验
        if(!EmptyUtils.isProjectBaseInfoListEmpty(projectBaseInfoVoList)){
            return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回结果
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                projectBaseInfoVoList, emptyObject, HttpStatus.OK);
    }

    /**
     * 添加项目的基本情况
     * @param enId              企业id
     * @param projectName       项目名
     * @param address           建设地点
     * @param industry          所属行业
     * @param totalInvestment   总投资
     * @param investmentCompleted   已完成投资
     * @param nextYearPlan          未来年计划
     * @param isScaleEnterprises    是否为规上企业
     * @param constructionContent   主要建设内容及规模
     * @param processDescription    主要工艺说明
     * @param progressInfo          项目进展情况
     * @param startTime             开工时间
     * @param completedTime         计划建成投产时间
     * @param userId                企业用户id
     * @param deleted               逻辑删除字段
     * @param session   Http回话对象内部存储当前登录的用户id  user_id / user_namen / role_id
     * @return
     */
    @PostMapping("/projectbase")
    @ApiOperation(value = "添加项目的基本情况",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enId",value = "企业id",dataType = "Long", paramType = "Long", required = true),
            @ApiImplicitParam(name = "projectName",value = "项目名称",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "address",value = "企业住所",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "industry",value = "所属行业",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "totalInvestment",value = "总投资",dataType = "Double", paramType = "Double", required = true),
            @ApiImplicitParam(name = "investmentCompleted",value = "已完成投资",dataType = "Double", paramType = "Double", required = true),
            @ApiImplicitParam(name = "nextYearPlan",value = "未来年计划",dataType = "Double", paramType = "Double", required = true),
            @ApiImplicitParam(name = "isScaleEnterprises",value = "是否为规上企业",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "constructionContent",value = "主要建设内容及规模",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "processDescription",value = "主要工艺说明",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "progressInfo",value = "项目进展情况",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "startTime",value = "开工时间",dataType = "Date", paramType = "Date", required = true),
            @ApiImplicitParam(name = "completedTime",value = "计划建成投产时间",dataType = "Date", paramType = "Date", required = true),
            @ApiImplicitParam(name = "userId",value = "用户ID",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "deleted",value = "逻辑删除字段",dataType = "Integer", paramType = "Integer", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> projectBaseAddMethod(Long enId,
                                                          String projectName,
                                                          String address,
                                                          String industry,
                                                          Double totalInvestment,
                                                          Double investmentCompleted,
                                                          Double nextYearPlan,
                                                          String isScaleEnterprises,
                                                          String constructionContent,
                                                          String processDescription,
                                                          String progressInfo,
                                                          @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)Date startTime,
                                                          @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)Date completedTime,
                                                          Integer userId,
                                                          Integer deleted,
                                                          @ApiIgnore HttpSession session){


        // 构建项目基本情况对象
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        projectBaseInfo.setEnId(enId);
        projectBaseInfo.setProjectName(projectName);
        projectBaseInfo.setAddress(address);
        projectBaseInfo.setIndustry(industry);
        projectBaseInfo.setTotalInvestment(totalInvestment);
        projectBaseInfo.setInvestmentCompleted(investmentCompleted);
        projectBaseInfo.setNextYearPlan(nextYearPlan);
        projectBaseInfo.setIsScaleEnterprises(isScaleEnterprises == null ? 0 : "on".equalsIgnoreCase(isScaleEnterprises) ? 1 : 0);
        projectBaseInfo.setConstructionContent(constructionContent);
        projectBaseInfo.setProcessDescription(processDescription);
        projectBaseInfo.setProgressInfo(progressInfo);
        projectBaseInfo.setStartTime(startTime);
        projectBaseInfo.setCompletedTime(completedTime);
        projectBaseInfo.setEnUserId(userId);
        projectBaseInfo.setDeleted(0);

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 如果当前登录的不是管理员用户(企业用户)
        // 获取当前登录的企业用户id 关联到企业 本关联只用来限制企业用户只查看自己
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
        if (role_id != 1) {

            projectBaseInfo.setEnUserId(user_id);
        }

        // 项目要件添加到数据库
        ProjectBaseInfo projectBaseInfo_new = projectBaseInfoService.insert(projectBaseInfo);


        // 判断插入数据库后的结果是否为空
        if(!EmptyUtils.isProjectBaseInfoEmpty(projectBaseInfo_new)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_INSERT_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        /**
         * 临时文件操作
         */
        // 将临时上传的目录内的文件移动到目标目录内

        String strDate = userId + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
        for(int i = 0; i < file_index; i++){
            // 构建临时文件全路径
            String resFileName = temp_path + tempfilename[i];
            String desFileName = des_path + strDate + ThreadLocalRandom.current().nextLong(System.currentTimeMillis()) + "-" + tempfilename[i];
            try {
                // 移动文件
                FileUtils.moveFile(new File(resFileName), new File(desFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 创建票据对象
            Bill bill = new Bill();
            bill.setProjectBaseInfoId(projectBaseInfo_new.getId());
            bill.setFilePath(desFileName);
            bill.setUrlPath(desFileName.split("static/")[1]);
            if (role_id != 1) {
                bill.setEnUserId(user_id);
            }else{
                bill.setEnUserId(userId);
            }
            bill.setDeleted(deleted);
            billService.insert(bill);
        }
        // 初始化此次回话共享变量
        file_index = 0;
        tempfilename = new String[10];

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_INSERT_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), projectBaseInfo_new, HttpStatus.OK);
    }

    /**
     * 修改项目的基本情况
     * @param id                主键id
     * @param enId              企业id
     * @param projectName       项目名
     * @param address           建设地点
     * @param industry          所属行业
     * @param totalInvestment   总投资
     * @param investmentCompleted   已完成投资
     * @param nextYearPlan          未来年计划
     * @param isScaleEnterprises    是否为规上企业
     * @param constructionContent   主要建设内容及规模
     * @param processDescription    主要工艺说明
     * @param progressInfo          项目进展情况
     * @param startTime             开工时间
     * @param completedTime         计划建成投产时间
     * @param userId                企业用户id
     * @param deleted               逻辑删除字段
     * @return
     */
    @PutMapping("/projectbase")
    @ApiOperation(value = "修改项目的基本情况",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键id",dataType = "Long", paramType = "Long", required = true),
            @ApiImplicitParam(name = "enId",value = "企业id",dataType = "Long", paramType = "Long", required = true),
            @ApiImplicitParam(name = "projectName",value = "项目名称",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "address",value = "企业住所",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "industry",value = "所属行业",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "totalInvestment",value = "总投资",dataType = "Double", paramType = "Double", required = true),
            @ApiImplicitParam(name = "investmentCompleted",value = "已完成投资",dataType = "Double", paramType = "Double", required = true),
            @ApiImplicitParam(name = "nextYearPlan",value = "未来年计划",dataType = "Double", paramType = "Double", required = true),
            @ApiImplicitParam(name = "isScaleEnterprises",value = "是否为规上企业",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "constructionContent",value = "主要建设内容及规模",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "processDescription",value = "主要工艺说明",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "progressInfo",value = "项目进展情况",dataType = "String", paramType = "String", required = true),
            @ApiImplicitParam(name = "startTime",value = "开工时间",dataType = "Date", paramType = "Date", required = true),
            @ApiImplicitParam(name = "completedTime",value = "计划建成投产时间",dataType = "Date", paramType = "Date", required = true),
            @ApiImplicitParam(name = "userId",value = "用户ID",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "deleted",value = "逻辑删除字段",dataType = "Integer", paramType = "Integer", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> projectBaseChangeByIdMethod(Long id,
                                                                 Long enId,
                                                                 String projectName,
                                                                 String address,
                                                                 String industry,
                                                                 Double totalInvestment,
                                                                 Double investmentCompleted,
                                                                 Double nextYearPlan,
                                                                 Boolean isScaleEnterprises,
                                                                 String constructionContent,
                                                                 String processDescription,
                                                                 String progressInfo,
                                                                 @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)Date startTime,
                                                                 @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)Date completedTime,
                                                                 Integer userId,
                                                                 Integer deleted,
                                                                 @ApiIgnore HttpSession session){

        if (!EmptyUtils.isLongEmpty(id) || !EmptyUtils.isLongEmpty(enId) || !EmptyUtils.isStringEmpty(projectName)
                || !EmptyUtils.isStringEmpty(address) || !EmptyUtils.isStringEmpty(industry)){
            return ReturnOperator.createResultMsg("", ServerStatus.PARAM_NOT_EMPTY, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 构建项目基本情况对象
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        projectBaseInfo.setId(id);
        projectBaseInfo.setEnId(enId);
        projectBaseInfo.setProjectName(projectName);
        projectBaseInfo.setAddress(address);
        projectBaseInfo.setIndustry(industry);
        projectBaseInfo.setTotalInvestment(totalInvestment);
        projectBaseInfo.setInvestmentCompleted(investmentCompleted);
        projectBaseInfo.setNextYearPlan(nextYearPlan);
        projectBaseInfo.setIsScaleEnterprises(isScaleEnterprises?1:0);
        projectBaseInfo.setConstructionContent(constructionContent);
        projectBaseInfo.setProcessDescription(processDescription);
        projectBaseInfo.setProgressInfo(progressInfo);
        projectBaseInfo.setStartTime(startTime);
        projectBaseInfo.setCompletedTime(completedTime);
        projectBaseInfo.setEnUserId(userId);
        projectBaseInfo.setDeleted(deleted);


        // 查询项目基本情况下面是否有之前票据内容
        List<Bill> billList = billService.queryByProjectBaseInfoId(projectBaseInfo.getId());
        // 存在有票据
        if (EmptyUtils.isBillListEmpty(billList)){
            // 进行循环删除
            for(Bill bill : billList) {
                // 构建票据文件存储位置对象
                File delFile = new File(bill.getFilePath());
                // 判断文件是否存在
                if(delFile.exists()) {
                    // 存在则删除
                    delFile.delete();
                }
                // 将数据库记录删除
                billService.deleteById(bill.getId());
            }
        }


        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 如果当前登录的不是管理员用户(企业用户)
        // 获取当前登录的企业用户id 关联到企业 本关联只用来限制企业用户只查看自己
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
        if (role_id != 1) {

            projectBaseInfo.setEnUserId(user_id);
        }

        // 项目要件添加到数据库
        ProjectBaseInfo projectBaseInfo_new = projectBaseInfoService.update(projectBaseInfo);

        // 判断插入数据库后的结果是否为空
        if(!EmptyUtils.isProjectBaseInfoEmpty(projectBaseInfo_new)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_INSERT_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        /**
         * 临时文件操作
         */
        // 将临时上传的目录内的文件移动到目标目录内

        String strDate = userId + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
        for(int i = 0; i < file_index; i++){
            // 构建临时文件全路径
            String resFileName = temp_path + tempfilename[i];
            String desFileName = des_path + strDate + ThreadLocalRandom.current().nextLong(System.currentTimeMillis()) + "-" + tempfilename[i];
            try {
                // 移动文件
                FileUtils.moveFile(new File(resFileName), new File(desFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 创建票据对象
            Bill bill = new Bill();
            bill.setProjectBaseInfoId(projectBaseInfo_new.getId());
            bill.setFilePath(desFileName);
            bill.setUrlPath(desFileName.split("static/")[1]);
            if (role_id != 1) {
                bill.setEnUserId(user_id);
            }else{
                bill.setEnUserId(userId);
            }
            bill.setDeleted(deleted);
            billService.insert(bill);
        }
        // 初始化此次回话共享变量
        file_index = 0;
        tempfilename = new String[10];


        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_UPDATE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), projectBaseInfo_new, HttpStatus.OK);
    }

    /**
     * 根据id删除项目基本情况
     * @param id    项目基本情况的id
     * @return
     */
    @DeleteMapping("/projectbase/{id}")
    @ApiOperation(value = "根据id删除项目基本情况",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id",value = "项目基本情况的id", required = true, dataType = "Long", paramType = "Long", dataTypeClass = Long.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> projectBaseDeleteByIdMethod(@PathVariable("id") Long id, @ApiIgnore HttpSession session){

        // 判断id是否为空
        if(!EmptyUtils.isLongEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }


        // 查询项目基本情况下面是否有之前票据内容
        List<Bill> billList = billService.queryByProjectBaseInfoId(id);
        // 存在有票据
        if (EmptyUtils.isBillListEmpty(billList)){
            // 进行循环删除
            for(Bill bill : billList) {
                // 构建票据文件存储位置对象
                File delFile = new File(bill.getFilePath());
                // 判断文件是否存在
                if(delFile.exists()) {
                    // 存在则删除
                    delFile.delete();
                }
                // 将数据库记录删除
                billService.deleteById(bill.getId());
            }
        }

        // 判断数据删除失败
        if(!projectBaseInfoService.deleteById(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_DELETE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }


        // 使用项目基本信息id 查询项目总能耗
        ProjectTotalEnergyconsumption projectTotalEnergyconsumption = projectTotalEnergyconsumptionService.queryProjectTotalInfoByProjectBaseInfoId(id);
        // 如果项目总能耗存在
        if(EmptyUtils.isProjectTotalEnergyconsumptionEmpty(projectTotalEnergyconsumption)){
            // 则删除
            projectTotalEnergyconsumptionService.deleteById(projectTotalEnergyconsumption.getId());
        }


        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), new Boolean(true), HttpStatus.OK);
    }

    /**
     * 根据id数组批量删除 项目基本情况
     * @param ids   项目基本情况的id数组
     * @return
     */
    @DeleteMapping("/projectbase/list")
    @ApiOperation(value = "根据id数组批量删除 项目基本情况",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "ids",value = "项目基本情况的id数组", required = true, dataType = "Long", paramType = "Long[]", dataTypeClass = Long.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> projectBaseDeleteListByIdMethod(Long[] ids, @ApiIgnore HttpSession session){

        // 参数校验
        if(!EmptyUtils.isIdsEmpty(ids)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                        new ArrayList(), emptyObject, HttpStatus.OK);
        }
        // 循环删除
        for(Long id : ids) {
            // 用项目基本情况的id去查询 票据表的project_base_info_id
            List<Bill> billList = billService.queryByProjectBaseInfoId(id);
            // 取到resources/static/tempupload/下路径
            String resources = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/static/upload";
            // 循环删除老的文件
            for(Bill bill : billList) {
                File old_file = new File(resources + bill.getFilePath());
                // 存在则删除
                if (old_file.exists()) {
                    old_file.delete();
                    // 删除数据库记录
                    billService.deleteById(bill.getId());
                }
            }
            projectBaseInfoService.deleteById(id);
            // 使用项目基本信息id 查询项目总能耗
            ProjectTotalEnergyconsumption projectTotalEnergyconsumption = projectTotalEnergyconsumptionService.queryProjectTotalInfoByProjectBaseInfoId(id);
            // 如果项目总能耗存在
            if(EmptyUtils.isProjectTotalEnergyconsumptionEmpty(projectTotalEnergyconsumption)){
                // 则删除
                projectTotalEnergyconsumptionService.deleteById(projectTotalEnergyconsumption.getId());
            }
        }

        // 返回结果
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), new Boolean(true), HttpStatus.OK);
    }


    /**
     * 多文件图片上传
     * @param files  文件数组对象
     * @return
     */
    @PostMapping("/uploadFile")
    @ApiOperation(value = "文件上传多次调用",produces = "application/json",consumes = "muiltipart-file/form-data")
    @ApiImplicitParam(name = "files",value = "文件数组对象", required = true, dataType = "Part", paramType = "Part[]", dataTypeClass = Part.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> upFileLoad(Part files) {

        // 上传文件校验
        if(!EmptyUtils.isNotFile(files)) {
            return ReturnOperator.createResultMsg("", ServerStatus.FILE_UPLOAD_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        synchronized (file_index){
            try{
                // 写入文件 实际写入到application.yml中配置的 spring.servlet.multipart.location
                // 也就是main目录下的resources下的static/tempupload 存放临时位置
                // tempfilename 临时存放文件名数组和file_index 代表几个文件索引也算几个文件
                // 获取提交的文件名
                String name = files.getSubmittedFileName();
                tempfilename[file_index] = name;
                files.write(name);
                file_index++;

            }catch (Exception e) {
                e.printStackTrace();
            }
        }


        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.FILE_UPLOAD_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), new Boolean(true), HttpStatus.OK);
    }
}
